/*
 *  文件流读写
 */

package com.wex.app.tools;

import ohos.app.Context;

import java.io.*;

public class FileTools {

    static public RandomAccessFile openReader(Context context, String name) {
        if (name == null)
            return null;
        File file = new File(context.getExternalMediaDirs()[0], name);
        if (file.exists()) {
            try {
                return new RandomAccessFile(file.getAbsolutePath(), "r");
            } catch (java.io.FileNotFoundException e) {
                System.out.println("-->> FileInputStream failed: " + file.getPath());
                return null;
            }
        }
        System.out.println("-->> file not found: " + file.getPath());
        return null;
    }

    static public RandomAccessFile openWriter(Context context, String name) {
        if (name == null)
            return null;
        File file = new File(context.getExternalMediaDirs()[0], name);
        try {
            if (file.exists())
                file.delete();
            if (!file.createNewFile()) {
                System.out.println("-->> createNewFile failed: " + file.getPath());
                return null;
            }
            return new RandomAccessFile(file.getAbsolutePath(), "rws");
        } catch (IOException e) {
            System.out.println("-->> FileOutputStream failed: " + file.getPath());
            return null;
        }
    }

    static public int read(RandomAccessFile raf, byte[] bytes) {
        try {
            if (raf != null)
            {
                int ret = raf.read(bytes);
                if (ret != bytes.length)
                    raf.seek(0);
                return ret;
            }
        } catch (IOException e) {}
        return 0;
    }

    static public void write(RandomAccessFile raf, byte[] bytes) {
        try {
            if (raf != null)
                raf.write(bytes);
        } catch (IOException e) {}
    }

    static public void write(RandomAccessFile raf, String s) {
        write(raf, s.getBytes());
    }

    static public void close(RandomAccessFile raf) {
        try {
            if (raf != null)
                raf.close();
        } catch (IOException e) {}
    }

}
